package org.haptimap.examples;

import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

import org.haptimap.hcimodules.touchovermap.*;

import android.content.pm.ActivityInfo;
import android.location.Location;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.util.Log;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;

import eu.telecom_bretagne.geotablet.R;
import eu.telecom_bretagne.utils.LogData;
import eu.telecom_bretagne.xml_parser.Node;
import eu.telecom_bretagne.xml_parser.ParserSAX;
import eu.telecom_bretagne.xml_parser.Way;

/**
 * Example for TouchOverMap using Android Maps API.
 * 
 * The layout for this example contains a MapView and a TouchOverlayView.
 * To use the MapView you will need to edit res/layout/main.xml and
 * add your Maps API key.
 * <p>
 * Get your Maps API key here: {@link http://code.google.com/intl/de-DE/android/add-ons/google-apis/mapkey.html}
 * <p>
 * Provide TouchOverlayView with:
 * <ul>
 *   <li>a implementation of the interface org.haptimap.hcimodules.touchovermap.Projection</li>
 *   <li>List&lt;Lines&gt;</li>
 *   <li>TextToSpeech (optional)</li>
 * </ul>
 */
public class TouchOverMapActivity extends MapActivity implements LinesProvider {
	
    private Location centerLocation = new Location("static");
    List<Line> linesList = new LinkedList<Line>();
    String latitude, longitude, region, city, road;
    int cercleSize;
    
    MapView mapView;
	TouchOverlayView olView;
	PointsOverlay ptsOverlay;
	LinesOverlay linesOverlay;
	TextToSpeech tts;
	LogData logData;
	
	final String LOG_TAG = "TOUCHOVERMAP-ACTIVITY";
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.mapview);
      
       region = getIntent().getStringExtra("region");
       city = getIntent().getStringExtra("city");
       road = getIntent().getStringExtra("road");
       latitude = getIntent().getStringExtra("latitude");
       longitude = getIntent().getStringExtra("longitude");
       cercleSize = getIntent().getIntExtra("cercleSize", 10);       
       
       centerLocation.setLatitude(Double.parseDouble(latitude));
       centerLocation.setLongitude(Double.parseDouble(longitude));
    }
    
    @Override
    protected void onStart()
    {
          super.onStart();
          this.loadMap();
    }
    @Override
    protected void onStop()
    {
    	try {
    		tts.shutdown();
			logData.closeFile();
		} catch (IOException e) {			
			e.printStackTrace();
		}
          super.onStop();
    }
    
    @Override
    protected void onDestroy()
    {
    	tts.shutdown();    	
		try {
			tts.shutdown();
			logData.closeFile();
		} catch (IOException e) {			
			e.printStackTrace();
		}    	
        super.onDestroy();
    }
    
    public void loadMap(){
    	
    	int zoom;    	
    	if (city.equals("Hamlet"))
    		zoom = 15;
    	else
    		zoom = 13;
    	
    	try {
			logData = new LogData(region);
		} catch (IOException e) {			
			e.printStackTrace();
		}
    	
    	// Initialize the MapView
           mapView = (MapView) findViewById(R.id.mapview);
           mapView.setBuiltInZoomControls(true);
           mapView.getController().setCenter(new GeoPoint( (int)(centerLocation.getLatitude()*1E6), (int)(centerLocation.getLongitude()*1E6) ));
           mapView.getController().setZoom(zoom);
           mapView.setDrawingCacheEnabled(true);
          // mapView.setSystemUiVisibility(MapView.STATUS_BAR_HIDDEN);
           setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
          
          // Initialize TouchOverlayView by setting Lines and Projection.
           olView = (TouchOverlayView) findViewById(R.id.touchoverlayview);           

           // As TouchOverlayView is independent from Android Maps API Projection needs to be implemented,
           olView.initialize(new GoogleProjection(mapView.getProjection()), this, this.cercleSize, logData);           
           
           // While TouchOverlayView is active, no touch event will be propagated to underlying views.
           // So set this to false to disable TouchOverlayView and enable e.g. map interaction
           olView.setActive(true);
           
           // Provide a TextToSpeech instance to allow speech feedback.
           // This will read out the name of the touched Line.
            tts = new TextToSpeech(this, new OnInitListener() {
   			public void onInit(int status) {
   				// ignore
   			}
   		});
           olView.setTts(tts);                 
           
           // Visual feedback is not included in TouchOver Map. 
           // For demonstration purposes LinesOverlay is included which draws red paths on the canvas
           List<Overlay> mapOverlays = mapView.getOverlays();           
           loadXMLPoints();
           mapOverlays.add(ptsOverlay);
          // mapOverlays.add(linesOverlay);
           
       }
    
	
	@SuppressWarnings("unchecked")
	public void loadXMLPoints(){
		
		String[] args = new String[3];
		args[0] = region;
		args[1] = city;
		args[2] = road;
		ParserSAX.main(args);
		HashMap<String,Object> result = ParserSAX.getParseResult();;
		List<Node> osm_nodes = (List<Node>) result.get("nodes");
		List<Way> osm_ways = (List<Way>) result.get("ways");

		if (osm_nodes != null){
			for(Node n : osm_nodes){
				Location location = new Location("singleNode");
				Line singlePointLine = new Line();
				
				location.setLatitude(n.getLat());
				location.setLongitude(n.getLon());
				
				singlePointLine.addElement(location);
				singlePointLine.setName(n.getName());
				linesList.add(singlePointLine);				
			}
			ptsOverlay = new PointsOverlay(linesList, cercleSize);
			for(Way w : osm_ways){
				if (w.getHighWay().equals("trunk")){
					Line way = new Line();
					for (Node n : w.getNodes()){
						Location location = new Location("way");
						String name = "";
						location.setLatitude(n.getLat());
						location.setLongitude(n.getLon());
						if (w.getName()!=null){
							name = w.getName();
						}
						way.addElement(location);						 
						way.setName(w.getRef() + " "+ name);
					}
					linesList.add(way);
				}				
			}
			linesOverlay = new LinesOverlay(linesList);
		}else{
			Log.i( LOG_TAG, "Can't load XML points");
		}
	
	}
	       
	    /*
	     * @see com.google.android.maps.MapActivity#isRouteDisplayed()
	     */
		@Override
		protected boolean isRouteDisplayed() {
			return false;
		}
	
		public List<Line> receiveLines(double tllat, double tllon, double brlat,
				double brlon) {
	        
	        List<Line> lines = new LinkedList<Line>();
			if (linesList!=null){
				 lines = linesList;
			}        
			
			return lines;
		}	
}